package cn.jekun.shop.common.service;

import java.math.BigDecimal;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.DateJsonValueProcessor;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Service;

import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
//import cn.jekun.component.core.DateJsonValueProcessor;
import cn.jekun.component.core.bean.gen.BaBusiness;
import cn.jekun.component.core.bean.gen.ErpDeliveryAddress;
import cn.jekun.component.core.bean.gen.ErpOrderMessage;
import cn.jekun.component.core.bean.gen.ErpOrderStatus;
import cn.jekun.component.core.bean.gen.ErpOrderType;
import cn.jekun.component.core.bean.gen.ErpOrders;
import cn.jekun.component.core.bean.gen.ErpShop;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.gen.BaBusinessService;
import cn.jekun.component.core.service.gen.ErpDeliveryAddressService;
import cn.jekun.component.core.service.gen.ErpOrderMessageService;
import cn.jekun.component.core.service.gen.ErpOrderStatusService;
import cn.jekun.component.core.service.gen.ErpOrderTypeService;
import cn.jekun.component.core.service.gen.ErpOrdersService;
import cn.jekun.component.core.service.gen.ErpShopService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.component.shop.service.SendMessageService;
import cn.jekun.shop.app.bean.Order;
import cn.jekun.shop.app.bean.ShopOrder;
import cn.jekun.shop.web.bean.OrderItem;

@Service(ShopOrderService.BEAN_NAME)
public class ShopOrderService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.common.service.ShopOrderService";
	@Override
	public String getNamespace() {
		return "SHOP_ORDER";
	}
	@Resource(name = cn.jekun.component.shop.service.OrderService.BEAN_NAME)
	cn.jekun.component.shop.service.OrderService orderService;
	@Resource(name = ErpOrdersService.BEAN_NAME)
	protected ErpOrdersService erpOrdersService;
	@Resource(name = RsUserService.BEAN_NAME)
	protected RsUserService rsUserService;
	@Resource(name = ErpOrderTypeService.BEAN_NAME)
	protected ErpOrderTypeService erpOrderTypeService;
	@Resource(name = ErpOrderStatusService.BEAN_NAME)
	protected ErpOrderStatusService erpOrderStatusService;
	@Resource(name = BaBusinessService.BEAN_NAME)
	protected BaBusinessService businessService;
	@Resource(name = ErpDeliveryAddressService.BEAN_NAME)
	protected ErpDeliveryAddressService addressService;
	@Resource(name=ErpOrderMessageService.BEAN_NAME)
	ErpOrderMessageService erpOrderMessageService;
	@Resource(name=SendMessageService.BEAN_NAME)
	SendMessageService sendMessageService;
	
	@Resource(name=ErpShopService.BEAN_NAME)
	protected ErpShopService erpShopService;
	/**
	 * 获取商家订单列表
	 * @param shopId
	 * @param status
	 * @param orderType
	 * @param businessType
	 * @param currentPage
	 * @param pageSize
	 * @param days
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject getOrders(
			@Security
			String shopId,
			@Security
			String status,
			@Security
			String orderType,
			@Security
			String businessType,
			@Security
			String currentPage,
			@Security
			String pageSize,
			Date endDate,
			@Security
			String memberId){
		JSONObject jsonObject = new JSONObject();
		Page page = new Page();
		if (StringUtils.isBlank(shopId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"商家代码不能为空");
		}
		if (StringUtils.isBlank(pageSize)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"页大小不能为空");
		}
		if (StringUtils.isBlank(currentPage)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"当前页不能为空");
		}
		page.setPageSize(Integer.parseInt(pageSize));
		page.setPageNumber(Integer.parseInt(currentPage));
		Map tempMap = new HashMap();
		if (StringUtils.isNotBlank(shopId)) {
			Map map = new HashMap();
			map.put(ErpShop.COL_PARENT_SHOP_ID, shopId);
			SqlUtis.prepareSql(map, SqlUtis.getSQL(map, "a."+ErpShop.COL_PARENT_SHOP_ID,Types.VARCHAR,SqlUtis.EQ));
			//判断shopId是不是拥有分店
			if(this.erpShopService.exists(map)){
				tempMap.put("parentShopId", shopId);
			}else{
				tempMap.put("shopId", shopId);
			}
		}
		if (StringUtils.isNotBlank(status)) {
			tempMap.put("status", status);
		}
		if (StringUtils.isNotBlank(orderType)) {
			tempMap.put("orderType", orderType);
		}
		if (StringUtils.isNotBlank(businessType)) {
			tempMap.put("businessType", businessType);
		}
		if (endDate!=null) {
			tempMap.put("date", DateFormatUtils.format(endDate,"yyyy-MM-dd"));
			}
		if (StringUtils.isNotBlank(memberId)) {
			tempMap.put("memberId", memberId);
			}
		List<ShopOrder> orderList = this.list(this.getStatementName("queryOrdersByShopId"),tempMap,page);
		for (int i = 0; i < orderList.size(); i++) {
			Map orderitemsMap = new HashMap();
			orderitemsMap.put("orderId", orderList.get(i).getOrderId());
			List picDefault = this.list(this.getStatementName("queryGoodsPicByOrderId"),orderitemsMap);
			orderList.get(i).setPicList(picDefault);
		}
		
		jsonObject.put("orderList", orderList);
		jsonObject.put("pageSize", page.getPageSize());
		jsonObject.put("currentPage", page.getPageNumber());
		jsonObject.put("totals", page.getPages());
		return executeRerutn(jsonObject); 
	}
	/**
	 * 订单操作
	 * @param orderId
	 * @return
	 */
	public JSONObject processOrder(
			@Security
			String userId,
			@Security
			String orderId,
			@Security
			String status,
			@Security
			String memo,
			@ErpOrders.AnnoCloseReason
			String reason){
		JSONObject jsonObject = new JSONObject();
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"用户编码不能为空");
		}
		if(StringUtils.isBlank(orderId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"订单号不能为空");
		}
		if(StringUtils.isBlank(status)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"操作码不能为空");
		}
		try {
			if (Constants.ERP_ORDER_STATUS.SHIPPING.equals(status)) {// 发货
				orderService.shippingOrderBySystem(userId, orderId, "发货");
				jsonObject.put("statusId",
				Constants.ERP_ORDER_STATUS.SHIPPING);
			} else if (Constants.ERP_ORDER_STATUS.CLOSED.equals(status)) {// 取消
				orderService.cancelOrderByShop(userId, orderId, memo==null?"取消订单":memo,reason);
				jsonObject.put("statusId", Constants.ERP_ORDER_STATUS.CLOSED);
			} else if (Constants.ERP_ORDER_STATUS.OK.equals(status)) {// 完成
				orderService.finishOrderByShop(userId, orderId, "完成");
				jsonObject.put("statusId", Constants.ERP_ORDER_STATUS.OK);
			} else {
				return this.executeRerutnFail(jsonObject);
			}

			return this.executeRerutn(jsonObject);
		} catch (BusinessException e) {
			throw e;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return this.executeRerutnFail(jsonObject);
	}
	/**
	 * 订单状态
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public JSONObject getOrderStatusList() {
		JSONObject jsonObject = new JSONObject();
		Map temp = new HashMap();
		ErpOrderStatus orderStatus = new ErpOrderStatus();
		List<ErpOrderStatus> list = erpOrderStatusService.list(temp);
		if(list != null){
			orderStatus.setOrderStatusId("");
			orderStatus.setOrderStatusName("全部");
		}
		list.add(0, orderStatus); 
		jsonObject.put("orderStatusList", list);
		return executeRerutn(jsonObject);
	}
	/**
	 * 订单类型
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public JSONObject getOrderTypeList() {
		JSONObject jsonObject = new JSONObject();
		Map temp = new HashMap();
		ErpOrderType orderType = new ErpOrderType();
		List<ErpOrderType> list = erpOrderTypeService.list(temp);
		
		if(list != null){
			orderType.setOrderTypeId("");
			orderType.setOrderTypeName("全部");
		}
		list.add(0,orderType);
		jsonObject.put("orderTypeList", list);
		return executeRerutn(jsonObject);
	}
	/**
	 * 订单业务类型
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public JSONObject getBusinessTypeList() {
		JSONObject jsonObject = new JSONObject();
		Map temp = new HashMap();
		BaBusiness business = new BaBusiness();
		List<BaBusiness> list = businessService.list(temp);
		if(list != null){
			business.setBusinessId("");
			business.setBusinessName("全部");
		}
		list.add(0, business);
		jsonObject.put("businessList", list);
		return executeRerutn(jsonObject);
	}
	/**
	 * 获取商家各种订单状态数量
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public JSONObject getOrderMessageList(String shopId) {
		JSONObject jsonObject = new JSONObject();
//		String sql = "select c.order_status_id as orderStatusId,order_status_name as orderStatusName,count(c.order_status_id) as nums from (select a.order_status_id,b.order_status_name from erp_orders a left join erp_order_status b on(a.order_status_id=b.order_status_id) where a.shop_id='"+shopId+"') c group by c.order_status_id,c.order_status_name";
		List list = this.getOrderTypeAndTotals(shopId);
		jsonObject.put("orderMessageList", list);
		return executeRerutn(jsonObject);
	}
	/**
	 * 获取商家各种订单状态数量(普通商家)
	 * @param shopId
	 * @return
	 */
	public List getOrderTypeAndTotals(String shopId){
		String sql = "select b.order_status_name as orderStatusName,b.order_status_id as orderStatusId,nvl2(t.nums,t.nums,0) as nums from erp_order_status b  left join( select a.order_status_id,count(1) nums from erp_orders a where a.shop_id = '"+shopId+"' group by order_status_id ) t  on (t.order_status_id = b.order_status_id)";
		List list = this.listBySql(sql);
		return list;
	}
	/**
	 * 获取商家各种订单状态数量(拥有分店)
	 * @param shopId
	 * @return
	 */
	public List getOrderTypeAndTotalsShops(String shopId){
		String sql = "select b.order_status_name as orderStatusName,b.order_status_id as orderStatusId,nvl2(t.nums,t.nums,0) as nums from erp_order_status b  left join( select a.order_status_id,count(1) nums from erp_orders a where a.shop_id in(select shop_id from erp_shop where shop_id='"+shopId+"' or parent_shop_id='"+shopId+"') group by order_status_id ) t  on (t.order_status_id = b.order_status_id)";
		List list = this.listBySql(sql);
		return list;
	}
	
	/**
	 * 订单详情
	 * @param orderId
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject getOrderDetail(
			@Security
			String orderId) {
		JSONObject jsonObject = new JSONObject();
		if(StringUtils.isBlank(orderId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"订单号不能为空");
		}
		//获取订单信息
		Map orderMap = new HashMap();
		orderMap.put("orderId", orderId);
		Order order = erpOrdersService.one(this.getStatementName("selectShopOrder"),orderMap);
		String deliverTime = "";
		String finishTime = "";
		if(order == null){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"订单不存在");
		}else{
			if(order.getDeliverTime()!=null){
				deliverTime = order.getDeliverTime();
			}
			if(order.getFinishTime() != null){
				finishTime = order.getFinishTime();
			}
		}
		
		//修改商家已读此订单
		ErpOrders updateOrder = new ErpOrders();
		updateOrder.setOrderId(orderId);
		updateOrder.setShopReaded("1");
		updateOrder.setShopReadedTime(new Date());
		this.erpOrdersService.update(updateOrder);
		
		jsonObject.put("deliverTime", deliverTime);
		jsonObject.put("finishTime", finishTime);
		jsonObject.put("paymentName", order.getPaymentName());
		jsonObject.put("shipTime", order.getShipTime());
		jsonObject.put("orderTime", order.getCreateTime());
		jsonObject.put("statusName", order.getStatusName());
		jsonObject.put("orderId", order.getOrderId());
		jsonObject.put("statusId", order.getStatusId());
		jsonObject.put("shopId", order.getShopId());
		jsonObject.put("shopName", order.getShopName());
		jsonObject.put("totalAmount", order.getTotalAmount());
		jsonObject.put("deliveryId", order.getDeliveryId());
		jsonObject.put("deliveryName", order.getDeliveryName());
		jsonObject.put("deliveryAmount", order.getDeliveryAmount());
		
		Double totalAmount = new BigDecimal(order.getTotalAmount()==null?0:order.getTotalAmount()).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
		Double deliveryAmount = order.getDeliveryAmount()==null?0:order.getDeliveryAmount();
		Double merchandiseAmount = new BigDecimal((totalAmount - deliveryAmount)<0?0:(totalAmount - deliveryAmount)).setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
		
		
		jsonObject.put("merchandiseAmount", merchandiseAmount);
		jsonObject.put("businessHours", order.getBusinessHours());
		//获取商品信息
		Map merchandiseMap = new HashMap();
		merchandiseMap.put("orderId", orderId);
		List<OrderItem> items = this.list(this.getStatementName("selectShopOrderItem"), merchandiseMap);
		jsonObject.put("items", items);
		
		//获取会员信息
		Map userMap = new HashMap();
		userMap.put(RsUser.COL_USER_ID, order.getUserId());
		SqlUtis.prepareSql(userMap, SqlUtis.getSQL(userMap, "a."+RsUser.COL_USER_ID,Types.VARCHAR,SqlUtis.EQ));
		RsUser user = rsUserService.one(userMap);
		if(user == null){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"会员不存在");
		}
		jsonObject.put("userInfo", user);
		
		//获取收货地址信息
		Map addressMap = new HashMap();
		ErpDeliveryAddress address = new ErpDeliveryAddress();
		if(order.getAddressId()!=null){
			addressMap.put(ErpDeliveryAddress.COL_ADDRESS_ID, order.getAddressId());
			SqlUtis.prepareSql(addressMap, SqlUtis.getSQL(addressMap, "a."+ErpDeliveryAddress.COL_ADDRESS_ID,Types.VARCHAR,SqlUtis.EQ));
			address = addressService.one(addressMap);
			
		}
		jsonObject.put("address", address);
		logger.info("====================订单留言================");
		//查看用户对订单的留言,最新的留言
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd HH:mm:ss")); 
		String sort = " a.create_time desc nulls last";
		Map orderMsgMap= new HashMap();
		orderMsgMap.put(ErpOrderMessage.COL_ORDER_ID, orderId);
		SqlUtis.prepareSql(orderMsgMap,SqlUtis.getSQL(orderMsgMap,"a."+ErpOrderMessage.COL_ORDER_ID,Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.orderBy(sort));
		List<ErpOrderMessage> orderMessagesList = erpOrderMessageService.list(orderMsgMap);
		ErpOrderMessage erpOrderMessage = new ErpOrderMessage();
		if(orderMessagesList != null && orderMessagesList.size() > 0 ){
			erpOrderMessage = orderMessagesList.get(0); //获取最新的一条留言
			String createName = erpOrderMessage.getCreateName();
			String type = erpOrderMessage.getType();
			RsUser tempUser = rsUserService.one(createName);
			erpOrderMessage.setCreateName(tempUser.getUserName());
			String orderMessageType = Constants.ERP_ORDER_MESSAGE_TYPE.ADD_ORDER.equals(type)?"【用户提交订单留言】":
				Constants.ERP_ORDER_MESSAGE_TYPE.APPEAL_BY_SHOP.equals(type)?"【商家申请客服留言】":
					Constants.ERP_ORDER_MESSAGE_TYPE.APPEAL_BY_USER.equals(type)?"【用户申请客服留言】":
						Constants.ERP_ORDER_MESSAGE_TYPE.REJECT_RECEIPT.equals(type)?"【用户拒绝收货留言】":"";
			erpOrderMessage.setContent(orderMessageType+erpOrderMessage.getContent());
		}
		JSONArray jsonArray = JSONArray.fromObject(erpOrderMessage, jsonConfig);
		if (jsonArray!=null && jsonArray.size()>0) {
			logger.info("===jsonObject="+jsonArray.get(0));
			jsonObject.put("erpOrderMessage", jsonArray.get(0));
		}else{
			jsonObject.put("erpOrderMessage", "");
		}
		logger.info("=================订单留言结束====================="+jsonObject);
		//判断是否允许取消订单
		ErpOrders tempOrder = this.erpOrdersService.one(orderId);
		String allowCancel = "0";//allowCancelCode(0:不允许取消操作   1:允许取消操作)
		if(this.orderService.allowCancelOrder(tempOrder, this.orderService.TYPE_SHOP)){
			allowCancel = "1";
		}
		jsonObject.put("allowCancel", allowCancel);
		//判断是否允许发货
		String allowSendGoodsCode = "0";//allowSendGoods(0:不允许发货操作   1:允许发货操作)
		if(this.orderService.allowShippingOrder(tempOrder,this.orderService.TYPE_SHOP)){
			allowSendGoodsCode = "1";
		}
		jsonObject.put("allowSendGoods", allowSendGoodsCode);
		//判断是否允许提醒用户收货
		String allowRemindToUser = "0";//allowRemindToUser(0:不允许提醒用户收货操作   1:允许提醒用户收货操作)
		if(this.orderService.allowRemind(tempOrder, this.orderService.REMIND_TO_USER)){
			allowRemindToUser = "1";
		}
		jsonObject.put("allowRemindToUser", allowRemindToUser);
		//判断是否允许申请客服介入
		String allowApplay = "0";//allowApplay(0:不允许申请操作   1:允许申请操作)
		if(this.orderService.allowApply(tempOrder)){
			allowApplay = "1";
		}
		jsonObject.put("allowApplay", allowApplay);
		//判断是否允许确认收货
		String allowAcceptGoods = "0";
		if(this.orderService.allowFinishOrder(tempOrder, this.orderService.TYPE_SHOP)){
			allowAcceptGoods = "1";
		}
		jsonObject.put("allowAcceptGoods", allowAcceptGoods);
		//超时消息
		jsonObject.put("timeoutMessage", this.orderService.getTimeoutMessage(tempOrder, this.orderService.TYPE_SHOP));
		return executeRerutn(jsonObject);
	}
	/**
	 * 打印订单
	 * @param orderId
	 * @return
	 */
	public JSONObject printOrder(
			@Security
			String orderId) {
		JSONObject jsonObject = new JSONObject();
		if(StringUtils.isBlank(orderId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"订单号不能为空");
		}
		try {
			ErpOrders orders = this.erpOrdersService.one(orderId);
//			this.sendMessageService.pushMessageToTerminals(orders, "onlyPrintOrder", "0");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return executeRerutn(jsonObject);
	}
	
}
